package org.mspring.mlog.freemarker.method;

import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModelException;
import org.apache.commons.lang3.StringUtils;
import org.mspring.mlog.service.ConfigEntityService;
import org.mspring.nbee.common.utils.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author Gao Youbo
 * @since 2015-01-04 13:24
 */
@Component
public class ConfigMethodModel implements TemplateMethodModelEx {
    private ConfigEntityService configEntityService;

    @Override
    public Object exec(List arguments) throws TemplateModelException {
        if (CollectionUtils.isEmpty(arguments)) {
            return StringUtils.EMPTY;
        }
        String group = getGroup(arguments);
        String name = getName(arguments);
        return configEntityService.getConfigValue(group, name);
    }

    protected String getGroup(List arguments) {
        if (CollectionUtils.isEmpty(arguments) || arguments.size() < 2) {
            return null;
        }
        return arguments.get(0).toString();
    }

    protected String getName(List arguments) {
        if (CollectionUtils.isEmpty(arguments) || arguments.size() < 2) {
            return null;
        }
        return arguments.get(1).toString();
    }

    @Autowired
    public void setConfigEntityService(ConfigEntityService configEntityService) {
        this.configEntityService = configEntityService;
    }
}
